const express = require('express');
let utils = require('../utils/utils');

let router = express.Router();

let db = require('../db/db');


//注册
router.get('/reg',(req,res)=>{
    res.render('admin/reg.ejs',{});
})
router.post('/reg',(req,res)=>{
    let password = utils.md5(req.body.password);
    let sql = `insert into blog_user (username,password) values ('${req.body.username}','${password}')`;
    db.query(sql).then((data)=>{
        if(data.affectedRows){
            req.flash('success','注册成功');
            res.redirect('/login/login');
        }else{
            req.flash('error','注册失败');
            res.redirect('back');
        }
    })
})
//登录
router.get('/login',(req,res)=>{
    res.render('admin/login.ejs',{});
})
router.post('/login',(req,res)=>{
    let password = utils.md5(req.body.password);
    // let sql = `insert into blog_user (username,password) values ('${req.body.username}','${password}')`;
    let sql = `select uid,username,avatar from blog_user where username='${req.body.username}' and password='${password}'`;
    db.query(sql).then((data)=>{
        if(data.length){
            req.session.user = data[0];
            req.flash('success','登录成功');
            res.redirect('/index');
        }else{
            req.flash('error','登录失败');
            res.redirect('back');
        }
    })
})

router.get('/logout',(req,res)=>{
    req.session.user = null;
    req.flash('success','退出成功');
    res.redirect('/index');
})
module.exports = router;
